package com.example.calendar.data.local.dao

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.example.calendar.data.model.Task
import com.example.calendar.data.model.TaskPriority
import kotlinx.coroutines.flow.Flow
import org.threeten.bp.LocalDateTime

@Dao
interface TaskDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertTask(task: Task): Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertTasks(tasks: List<Task>): List<Long>

    @Update
    suspend fun updateTask(task: Task)

    @Delete
    suspend fun deleteTask(task: Task)

    @Query("UPDATE tasks SET isDeleted = 1, updatedAt = :now WHERE id = :taskId")
    suspend fun softDeleteTask(taskId: String, now: LocalDateTime = LocalDateTime.now())

    @Query("SELECT * FROM tasks WHERE id = :taskId AND isDeleted = 0")
    fun getTaskById(taskId: String): Flow<Task?>

    @Query("SELECT * FROM tasks WHERE isDeleted = 0 ORDER BY dueDate ASC")
    fun getAllTasks(): Flow<List<Task>>

    @Query("SELECT * FROM tasks WHERE isDeleted = 0 AND isCompleted = :isCompleted ORDER BY dueDate ASC")
    fun getTasksByCompletionStatus(isCompleted: Boolean): Flow<List<Task>>

    @Query("SELECT * FROM tasks WHERE isDeleted = 0 AND dueDate IS NOT NULL AND DATE(dueDate) = DATE(:date) ORDER BY dueDate ASC")
    fun getTasksForDate(date: LocalDateTime): Flow<List<Task>>

    @Query("SELECT * FROM tasks WHERE isDeleted = 0 AND dueDate IS NOT NULL AND DATE(dueDate) <= DATE(:date) AND isCompleted = 0 ORDER BY dueDate ASC")
    fun getOverdueTasks(date: LocalDateTime = LocalDateTime.now()): Flow<List<Task>>

    @Query("SELECT * FROM tasks WHERE isDeleted = 0 AND categoryId = :categoryId ORDER BY dueDate ASC")
    fun getTasksByCategory(categoryId: String): Flow<List<Task>>

    @Query("SELECT * FROM tasks WHERE isDeleted = 0 AND priority = :priority ORDER BY dueDate ASC")
    fun getTasksByPriority(priority: TaskPriority): Flow<List<Task>>
    
    @Query("SELECT * FROM tasks WHERE isDeleted = 0 AND (title LIKE '%' || :query || '%' OR description LIKE '%' || :query || '%') ORDER BY dueDate ASC")
    fun searchTasks(query: String): Flow<List<Task>>

    @Query("UPDATE tasks SET isCompleted = :completed, completedDate = CASE WHEN :completed = 1 THEN :now ELSE NULL END, updatedAt = :now WHERE id = :taskId")
    suspend fun updateTaskCompletionStatus(taskId: String, completed: Boolean, now: LocalDateTime = LocalDateTime.now())

    @Query("SELECT COUNT(*) FROM tasks WHERE isDeleted = 0 AND isCompleted = 0")
    fun getIncompleteTaskCount(): Flow<Int>
} 